#!/usr/bin/env python
"""
Parses the dmq config file and start/stop/restarts
dmq processes for the system.
"""

import os 
import sys
import getopt
import ConfigParser

import djangodmq.log as log

from djangodmq.appserver import AppServer
daemon_class = AppServer

#----------------------------------------------------------------------------
# Main 
#----------------------------------------------------------------------------

if __name__ == "__main__":

	this_dir = os.path.dirname(os.path.realpath(__file__))

	def usage():
		print " main.py -f <path_to_config_file> <action[start|stop|restart>"
		print " -f = The path to the service config file"
		print " -h = help"
		print " the action argument is required and must be start, stop or restart"
		sys.exit(2)

	try:
		opts, args = getopt.getopt(sys.argv[1:], "hf:")
	except getopt.GetoptError, err:
		print str(err)
		usage()
	for opt, val in opts:
		if opt == "-h":
			usage()
		elif opt == "-f":
			cfgpath = val
		else:
			assert False, "unhandled option"
			usage()

	print("Opening config file:%s" % (cfgpath))
	# Open and parse our config file
	cfg = ConfigParser.SafeConfigParser({'zmq_debug':False})
	try:
		# Make sure we can access the config file
		if not os.access( cfgpath, os.F_OK | os.R_OK ):
			raise( "Unable to access/open config file at:%s" % ( cfgpath ) )

		cfg.read( cfgpath )
	except Exception, e:
		print( "Exception: %s" % e )
		usage()

	daemon = None
	try:

		if len(args) != 1:
			print "Must supply only one argument of start, stop or restart."
			usage()

		action = args[0]
		if action not in ('start','stop','restart'):
			print "Must supply only one argument of start, stop or restart."
			usage()

		cfg_section = "DEFAULT"

		log_dir = cfg.get( cfg_section, 'log_dir' )
		log_file = cfg.get( cfg_section, 'log_file' )
		log_level = cfg.get( cfg_section, 'log_level' )
		print("Starting logger.\n\tlog_dir:%s\n\tlog_file:%s\n\tlog_level:%s" % (
				log_dir, log_file,log_level) )
		log.start_logger( log_dir, log_file, log_level)

		pid_dir = cfg.get( cfg_section, 'pid_dir' )
		pid_file = cfg.get( cfg_section, 'pid_file' )
		pidfile = "%s/%s" % (pid_dir, pid_file)
	
		zmq_host = cfg.get( cfg_section, 'zmq_host' )
		zmq_port = cfg.getint( cfg_section, 'zmq_port' )
		zmq_transport = cfg.get( cfg_section, 'zmq_transport' )
		zmq_debug = cfg.getboolean( cfg_section, 'zmq_debug' )
		app_settings_file = os.path.normpath(cfg.get( cfg_section, 'app_settings_file' ))

		dargs = ( pidfile, zmq_host, zmq_port, zmq_transport, zmq_debug,  app_settings_file)
		dkwargs = {
				'procname':'dmq',
				'stdin':cfg.get( cfg_section, 'stdin' ),
				'stdout':cfg.get( cfg_section, 'stdout' ),
				'stderr':cfg.get( cfg_section, 'stderr' ) }
			
		daemon = daemon_class(*dargs, **dkwargs) 

		if 'start' == action:
			log.log( "main starting %s" % (daemon.__class__.__name__), 'info' )
			daemon.start()
		elif 'stop' == action:
			log.log( "main stoping %s" % (daemon.__class__.__name__) , 'info' )
			daemon.stop()
		elif 'restart' == action:
			log.log( "main restarting %s" % (daemon.__class__.__name__), 'info' )
			daemon.restart()
		else:
			usage()

	except Exception as e:
		log.log( "main: pokemon exception: %s" % e, 'critical' )
		import traceback
		traceback.print_exc( e )
		sys.exit(2)

	sys.exit(0)
